# -*- coding: utf-8 -*-
import os
import time
import unittest

from app.helper import app_global
from app.http.services.base_service import BaseService
from app.lib.html_test_runner import HTMLTestRunnerCN
from app.helper.helper import report_path, root_path


class CaseService(BaseService):
    """case服务类"""

    def __init__(self, excel_data):
        super().__init__()

        app_global.auto_excel_data = excel_data

        self.testcase_path = os.path.join(root_path(), "app/http/services")

        self.report_title = self.config.get("report", "title")
        self.report_desc = self.config.get("report", "desc")
        self.report_tester = self.config.get("report", "tester")

        # report文件名
        now = time.strftime("%Y-%m-%d-%H-%M-%S")
        self.report_filename = 'report-{name}.html'.format(name=now)
        self.report_filepath = os.path.join(report_path(), self.report_filename)

    def run(self):
        discover = unittest.defaultTestLoader.discover(self.testcase_path, pattern='case_auto_test_service*.py')

        with open(self.report_filepath, "wb") as f:
            runner = HTMLTestRunnerCN.HTMLTestReportCN(stream=f, title=self.report_title,
                                                       description=self.report_desc,
                                                       tester=self.report_tester)
            runner.run(discover)

        return {"report_name": self.report_filename}
